package io.kiki.stack.http.feign.SpringMvcContract.annotation;

import io.kiki.stack.http.feign.MethodMetadata;
import io.kiki.stack.http.feign.SpringMvcContract.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.MatrixVariable;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.stream.Collectors;

import static io.kiki.stack.http.feign.Util.checkState;
import static io.kiki.stack.http.feign.Util.emptyToNull;

/**
 * {@link MatrixVariable} annotation processor.
 * <p>
 * Can expand maps or single objects. Values are assigned from the objects
 * {@code toString()} method.
 */
public class MatrixVariableParameterProcessor implements AnnotatedParameterProcessor {

    private static final Class<MatrixVariable> ANNOTATION = MatrixVariable.class;

    @Override
    public Class<? extends Annotation> getAnnotationType() {
        return ANNOTATION;
    }

    @Override
    public boolean processArgument(AnnotatedParameterContext annotatedParameterContext, Annotation annotation, Method method) {
        int parameterIndex = annotatedParameterContext.getParameterIndex();
        Class<?> parameterType = method.getParameterTypes()[parameterIndex];
        MethodMetadata data = annotatedParameterContext.getMethodMetadata();
        String name = ANNOTATION.cast(annotation).value();

        checkState(emptyToNull(name) != null, "MatrixVariable annotation was empty on param %s.", annotatedParameterContext.getParameterIndex());

        annotatedParameterContext.setParameterName(name);

        if (Map.class.isAssignableFrom(parameterType)) {
            data.indexToExpander().put(parameterIndex, this::expandMap);
        } else {
            data.indexToExpander().put(parameterIndex, object -> ";" + name + "=" + object.toString());
        }

        return true;
    }

    @SuppressWarnings("unchecked")
    private String expandMap(Object object) {
        Map<String, Object> paramMap = (Map) object;

        return paramMap.keySet().stream().filter(key -> paramMap.get(key) != null).map(key -> ";" + key + "=" + paramMap.get(key).toString()).collect(Collectors.joining());
    }

}
